<?php

namespace app\common\model;

use think\Db;
use think\Model;

class User extends Base
{

    protected $redata;

    public function _initialize()
    {
        $this->redata = ['content' => '', "status" => 0, 'msg' => ''];
    }


    /**
     * 快捷方法 返回出错信息
     */
    protected function err($msg)
    {
        $this->redata['msg'] = $msg;
        $this->redata['status'] = 0;
        return $this->redata;
    }

    /**
     * 快捷方法 返回成功
     */
    protected function suc($data = '')
    {
        $this->redata['content'] = $data;
        $this->redata['status'] = 1;
        return $this->redata;
    }


    /**
     * 修改赏金 魅力 积分
     * $cid 用户编码
     * $score 修改值
     * $sign 1-增加 2-减少
     * type 1-魅力 2-积分 3-赏金 4-钱包
     * $followId  促成交易用户编码
     * $source 来源 1-平台 2-后台人工 3-刷脸登记 4-实名认证 5-资料完善 6-安全培训 7-安全考试 8-邀请好友
     * $res status 1-成功 0-失败
     *
     */
    public function editScore($cid = 0, $sign = 0, $score = 0, $type = 0, $source = 0, $followId = 0, $orderId = 0)
    {
        //判断类型

        if (empty($cid)) {
            return $this->err('缺少用户主键！');
        }

        if ($sign != 1 && $sign != 2) {
            return $this->err('修改类型错误！');
        }
        if (empty($score)) {
            return $this->err('缺少修改数量！');
        }

        if ($type != 1 && $type != 2 && $type != 3 && $type != 4) {
            return $this->err('缺少选择类型！');
        }

        if ($source != 1 && $source != 2 && $source != 3 && $source != 4 && $source != 5 && $source != 6 && $source != 7 && $source != 8) {
            return $this->err('修改类型错误！');
        }

        $l_data = [
            'cid' => $cid,
            'sign' => $sign,
            'score' => $score,
            'source' => $source,
            'createTime' => createTime()
        ];
        $user = $this->field('id,reward,charm,points,money')->where(['id' => $cid])->find();
        switch ($type) {
            //修改魅力值
            case 1 :
                if ($sign == 1) {
                    $data = [
                        'id' => $cid,
                        'charm' => $user['charm'] + $score,
                    ];
                } else {
                    if ($user['charm'] < $score) {
                        return $this->err('魅力分总值不能小于0！');
                    }
                    $data = [
                        'id' => $cid,
                        'charm' => $user['charm'] - $score,
                    ];
                }

                $l_data['leftScore'] = $data['charm'];
                $l_data['inviteCid'] = $followId;
//                model('user_charm_log')->editData($l_data);
                db('user_charm_log')->insert($l_data);
                $res = $this->where(['id'=>$cid])->update($data);
                if (!$res) {
                    return $this->err('修改失败！');
                }
                return $this->suc($res);
                break;

            //修改积分
            case 2 :
                if(!empty($orderId)){
                    $l_data['orderId']=$orderId;
                }

                if ($sign == 1) {
                    $data = [
                        'id' => $cid,
                        'points' => $user['points'] + $score,
                    ];
                } else {
                    if ($user['points'] < $score) {
                        return $this->err('积分总值不能小于0！');
                    }
                    $data = [
                        'id' => $cid,
                        'points' => $user['points'] - $score,
                    ];

                }
                $l_data['leftScore'] = $data['points'];
 //               model('user_points_log')->editData($l_data);
                db('user_points_log')->insert($l_data);
                $res = $this->where(['id'=>$cid])->update($data);
                if (!$res) {
                    return $this->err('修改失败！');
                }
                return $this->suc($res);
                break;
            //修改赏金
            case 3 :
                if(!empty($followId)){
                    $l_data['followId']=$followId;
                }
                if(!empty($orderId)){
                    $l_data['orderId']=$orderId;
                }
                if ($sign == 1) {
                    $data = [
                        'reward' => $user['reward'] + $score,
                    ];
                }else {
                    if ($user['reward'] < $score) {
                        return $this->err('赏金余额不能小于0！');
                    }
                    $data = [
                        'reward' => $user['reward'] - $score,
                    ];
                }

                $l_data['leftScore'] = $data['reward'];
                $l_data['followId'] = $followId;
                //$res = model('user_reward_log')->editData($l_data);
                db('user_reward_log')->insert($l_data);
                $res = $this->where(['id'=>$cid])->update($data);
                break;
            case 4 :
                if ($sign == 1) {
                    $data = [
                        'id' => $cid,
                        'money' => $user['money'] + $score,
                    ];
                } else {
                    if ($user['money'] < $score) {
                        return $this->err('钱包余额不能小于0！');
                    }
                    $data = [
                        'id' => $cid,
                        'money' => $user['money'] - $score,
                    ];
                }
                $money_data = [
                    'targetId' => $cid,
                    'orderId' => $orderId,
                    'moneyType' => $sign,
                    'money' => $score,
                    'leftMoney' => $data['money'],
                    'orderSrc' => $source,
                    'createTime' => createTime()
                ];
                if(!empty($orderId)){
                    $money_data['orderId']=$orderId;
                }
 //               model('user_money_log')->editData($money_data);
                db('user_money_log')->insert($money_data);
                $res = $this->where(['id'=>$cid])->update($data);
                if (!$res) {
                    return $this->err('修改失败！');
                }
                return $this->suc($res);
                break;
            default:
                return $this->err('选择类型错误！');
                break;
        }
    }

    /**
     * 获取用户位置
     */
    public function getUserPosition($latitude=0,$longitude=0)
    {

        //验证参数
        if (empty($latitude)) {
           return $this->err('缺少latitude');
        }
        if (empty($longitude)) {
          return  $this->err('缺少longitude');
        }
        //百度API
        $bdApi = 'http://api.map.baidu.com/geocoder/v2/?ak=' . config('ak') . '&location=' . $latitude . ',' . $longitude . '&output=json&pois=1';
        $data = sendRequest($bdApi);
        $dataArray = json_decode($data, true);
        if ($dataArray['status'] == 0) {
            $res = [
                'address' => $dataArray['result']['formatted_address'],
                'location' => $dataArray['result']['location'],
                'addressComponent' => $dataArray['result']['addressComponent']
            ];
          return   $this->suc($res);
        } else {
            return  $this->err('百度api调取失败！！！');
        }
    }

    /**
     * 消息模板
     */
    public function sendMsgLater($touser=0,$form_id=0,$data=0,$template_id=0,$page=0,$timeLater=0){
        sleep($timeLater);
        //验证参数合法
        if(empty($touser)){
            return $this->err('缺少touser！');
        }
        if(empty($form_id)){
            return $this->err('缺少form_id！');
        }
        if(empty($data)){
            return $this->err('缺少data！');
        }
        if(empty($template_id)){
            return $this->err('缺少template_id！');
        }
        if(empty($page)){
            return $this->err('缺少page！');
        }
        if(empty($timeLater)){
            return $this->err('缺少timeLater！');
        }


        $AppId = config('wechat.AppId');
        $AppSecret = config('wechat.AppSecret');

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $AppId . '&secret=' . $AppSecret;

        $res = sendRequest($url);
        $token = json_decode($res)->access_token;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token;

        $data = [
            'touser' => $touser,
            'form_id' => $form_id,
            'data' => json_decode($data),
            'template_id' => $template_id,
            'page' => $page
        ];

        $expect = $this->field('isPartner')->where(['openid' => $touser])->find();
        if($expect['isPartner']!=1){
            $rep = curlPostWx($url, $data);
        }else{
            return $this->suc(1);
        }

    }


}
